<?php

namespace App\Http\Controllers\Api;

use App\Models\EmailSms;
use App\Models\PhoneSms;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
use Cloud;

class SmsController extends Controller
{
    /**
     * 发送邮箱验证码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function send_email_code(Request $request)
    {
        $email = $request->get('email');
        $type = $request->get('type');
        //验证参数
        if (empty($email) || empty($type)) {
            //参数错误
            return respF(1003);
        }
        //查找用户
        $user = User::where('email', $email)->first();
        //注册时邮箱必须未注册
        if ($type == 2) {
            if (collect($user)->count() > 0) {
                //邮箱已注册
                return respF(2019);
            }
        }
        //非注册判断用户是否存在
        if ($type != 2) {
            if (!$user) {
                //用户不存在
                return respF(1001);
            }
        }
        //查找验证码
        $sms = EmailSms::where(['email' => $email, 'type' => $type])->orderBy('created_at', 'desc')->first();
        //如果存在
        if ($sms) {
            //判断是否过期
            $expire_time = $sms->expire_time;
            //未过期，不能发
            if (time() < (int) $expire_time) {
                //验证码已发送 （不能报错）
                return response()->json(['status' => 1, 'msg' => '验证码已发送', 'expire_time' => $sms->expire_time]);
            }
        }

        $name = 'admin';
        $code = getCode();
        $flag = Mail::raw('你好，您的验证码是:   '.$code, function ($message) use ($email) {
            $to = $email;
            $message->to($to)->subject('系统邮件');
        });
        /*$data['email'] = $email;
        $data['code'] = $code;
        $data['name'] = $name;
        $flag = Mail::send('email', $data, function ($message) use ($data) {
            $message->to($data['email'], $data['code'])->subject('系统邮件');
        });*/

        if (!$flag) {
            $time = time();
            $expire_time = time() + 300;
            $res = EmailSms::create(
                [
                    'email' => $email,
                    'type' => $type,
                    'code' => $code,
                    'send_time' => $time,
                    'expire_time' => $expire_time,
                ]
            );

            return response()->json(['status' => 1, 'msg' => '发送成功', 'expire_time' => $res->expire_time]);
        } else {
            //获取验证码失败
            return respF(1023);
        }
    }

    /**
     * 发送手机验证码
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function send_phone_code(Request $request)
    {
        $phone = $request->get('phone');
        $type = $request->get('type');
        //验证参数
        if (empty($phone) || empty($type)) {
            //参数错误
            return respF(1003);
        }
        //查找用户
        $user = User::where('phone', $phone)->first();

        //注册判断用户是否已注册
        if ($type == 2) {
            if (collect($user)->count() > 0) {
                //该手机已注册
                return respF(2020);
            }
        }
        //非注册判断用户是否存在
        if ($type != 2) {
            if (!$user) {
                //用户不存在
                return respF(1001);
            }
        }
        //查找验证码
        $sms = PhoneSms::where(['phone' => $phone, 'type' => $type])->orderBy('created_at', 'desc')->first();
        //如果存在
        if ($sms) {
            //判断是否过期
            $expire_time = $sms->expire_time;
            //未过期，不能发
            if (time() < (int) $expire_time) {
                //验证码已发送 （不能报错）
                return response()->json(['status' => 1, 'msg' => '验证码已发送', 'expire_time' => $sms->expire_time]);
            }
        }

        $template = getTemplate($type); //根据类型获取短信模板
        $code = getCode();
        $expired = 300; //过期时间5分钟
        //$result = Cloud::sendTemplateSMS($phone, [$code, $expired.'秒'], $template); //发送短信验证码
        //发送失败
        //if (!$result['resultStatus']) {
        //return response()->json(['status' => 0, 'msg' => '发送失败']);
        //} else {
        $time = time();
        $expire_time = time() + $expired;
        $res = PhoneSms::create(
                [
                    'phone' => $phone,
                    'type' => $type,
                    'code' => $code,
                    'send_time' => $time,
                    'expire_time' => $expire_time,
                ]
            );

        return response()->json(['status' => 1, 'msg' => '发送成功', 'expire_time' => $res->expire_time]);
        //}
    }

    /**
     * 检查验证码是否正确.
     *
     * @author hxq
     */
    public function validator_code(Request $request)
    {
        //手机或邮箱
        $account = $request->get('account');
        //验证码类型
        $type = $request->get('type');
        //验证码
        $code = $request->get('code');
        //验证参数
        if (empty($account) || empty($type) || empty($code)) {
            return respF(1003);
        }
        //默认放过，正式上线去掉
        if ($code == '666666') {
            return response()->json(['status' => 1, 'msg' => '验证成功']);
        }

        //判断手机还是邮箱
        if (isPhone($account)) {
            $sms = PhoneSms::where(['phone' => $account, 'type' => $type])->orderBy('created_at', 'desc')->first();
        } elseif (isEmail($account)) {
            $sms = EmailSms::where(['email' => $account, 'type' => $type])->orderBy('created_at', 'desc')->first();
        } else {
            return respF(2011);
        }
        //没有数据
        if (collect($sms)->count() == 0) {
            return respF(3005);
        }
        //验证验证码
        if ($sms->code != $code) {
            return respF(3007);
        }
        //验证码已过期
        if ($sms->expire_time < time()) {
            return respF(3006);
        }

        return response()->json(['status' => 1, 'msg' => '验证成功']);
    }
}
